//
//  CourseSortListViewController.m
//  TeacherNet
//
//  Created by slz on 2017/11/13.
//  Copyright © 2017年 bnsr. All rights reserved.
//

#import "CourseSortListViewController.h"
#import "CourseSortDataModel.h"
#import "CourseTableViewCell.h"
#import "CourseModel.h"
#import "MoreCourseTableViewCell.h"
#import "CourseDetailViewController.h"

@protocol CourseSortMenuViewDelegate<NSObject>
- (void)sortViewClickByState:(CourseSortState)state;
- (void)sortViewClickByWork:(CourseWorkState)state;
- (void)sortViewClickByModelId:(NSString *)modelId;
@end

typedef enum
{
    CourseMenuStateShowSort,
    CourseMenuStateShowCourse,
    CourseMenuStateNone,
}CourseMenuState;

@interface CourseMenuButton : UIButton
@property(nonatomic,assign) BOOL selectState;
@end

@implementation CourseMenuButton

+ (instancetype)initWithTitlt:(NSString *)title target:(id)target andSelector:(SEL)sel
{
    CourseMenuButton * button = [CourseMenuButton buttonWithType:UIButtonTypeCustom];
    UIFont * font = [UIFont systemFontOfSize:15];
    CGFloat buttonWidth = [title widthForFont:font] + 16;
    button.size = CGSizeMake(buttonWidth, 20);
    button.titleLabel.font = font;
    [button setTitle:title forState:UIControlStateNormal];
    [button addTarget:target action:sel forControlEvents:UIControlEventTouchUpInside];
    return button;
}

- (void)setSelectState:(BOOL)selectState{
    if (selectState){
        [self setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
        self.layer.cornerRadius = 3;
        self.layer.borderWidth = 1;
        self.layer.borderColor = [UIColor greenColor].CGColor;
        self.layer.masksToBounds = YES;
    }else{
        self.layer.cornerRadius = 0;
        self.layer.borderWidth = 0;
        self.layer.masksToBounds = NO;
        [self setTitleColor:kDark_TextColor_Default forState:UIControlStateNormal];
    }
}
@end




@interface CourseSortView : UIView
@property (nonatomic,strong) UILabel *titleLabel1;
@property (nonatomic,strong) UILabel *titleLabel2;
@property (nonatomic,weak) id <CourseSortMenuViewDelegate>delegate;
@end

@implementation CourseSortView
{
    UIView * _topButtonBackView;
    UIView * _bottomButtonBackView;
    
}
- (instancetype)init
{
    self = [super init];
    if (self){
        NSInteger buttonHeight = 20;
        NSInteger secondLineTop = 60;
        
        _topButtonBackView = [UIView new];
        _topButtonBackView.frame = CGRectMake(0, 20, kScreenWidth, buttonHeight);
        [self addSubview:_topButtonBackView];
        
        _bottomButtonBackView = [UIView new];
        _bottomButtonBackView.frame = CGRectMake(0, secondLineTop, kScreenWidth, buttonHeight);
        [self addSubview:_bottomButtonBackView];
        
        self.backgroundColor = [UIColor whiteColor];
        _titleLabel1 = [UILabel new];
        _titleLabel1.text = @"状态";
        _titleLabel1.textColor = kLight_TextColor_Default;
        _titleLabel1.fontSize = 15;
        _titleLabel1.left = 11;
        _titleLabel1.top = 0;
        _titleLabel1.size = CGSizeMake(35, 20);
        [_topButtonBackView addSubview:_titleLabel1];
        
        _titleLabel2 = [UILabel new];
        _titleLabel2.text = @"排序";
        _titleLabel2.textColor = kLight_TextColor_Default;
        _titleLabel2.fontSize = 15;
        _titleLabel2.left = 11;
        _titleLabel2.top = 0;
        _titleLabel2.size = CGSizeMake(35, 20);
        [_bottomButtonBackView addSubview:_titleLabel2];
        
        
        CourseMenuButton * button1 = [CourseMenuButton initWithTitlt:@"全部" target:self andSelector:@selector(topButtonClick:)];
        button1.selectState = YES;
        button1.tag = 1;
        button1.origin = CGPointMake(_titleLabel1.right + 8, 0);
        [_topButtonBackView addSubview:button1];
        
        CourseMenuButton * button2 = [CourseMenuButton initWithTitlt:@"正在进行" target:self andSelector:@selector(topButtonClick:)];
        button2.selectState = NO;
        button2.tag = 2;
        button2.origin = CGPointMake(button1.right + 8, 0);
        [_topButtonBackView addSubview:button2];
        
        CourseMenuButton * button3 = [CourseMenuButton initWithTitlt:@"即将开始" target:self andSelector:@selector(topButtonClick:)];
        button3.selectState = NO;
        button3.tag = 3;
        button3.origin = CGPointMake(button2.right + 8, 0);
        [_topButtonBackView addSubview:button3];
        
        CourseMenuButton * button4 = [CourseMenuButton initWithTitlt:@"已结束" target:self andSelector:@selector(topButtonClick:)];
        button4.selectState = NO;
        button4.tag = 4;
        button4.origin = CGPointMake(button3.right + 8, 0);
        [_topButtonBackView addSubview:button4];
        
        CourseMenuButton * button5 = [CourseMenuButton initWithTitlt:@"最新" target:self andSelector:@selector(bottomButtonClick:)];
        button5.selectState = YES;
        button5.tag = 7;
        button5.origin = CGPointMake(_titleLabel2.right + 8, 0);
        [_bottomButtonBackView addSubview:button5];
        
        CourseMenuButton * button6 = [CourseMenuButton initWithTitlt:@"热门" target:self andSelector:@selector(bottomButtonClick:)];
        button6.selectState = NO;
        button6.tag = 6;
        button6.origin = CGPointMake(button5.right + 8, 0);
        [_bottomButtonBackView addSubview:button6];
        
        CourseMenuButton * button7 = [CourseMenuButton initWithTitlt:@"推荐" target:self andSelector:@selector(bottomButtonClick:)];
        button7.selectState = NO;
        button7.tag = 5;
        button7.origin = CGPointMake(button6.right + 8, 0);
        [_bottomButtonBackView addSubview:button7];
        
    }
    return self;
}

- (void)topButtonClick:(CourseMenuButton *)button{
    [self clearTopButtonSelectState];
    button.selectState = YES;
    if ([self.delegate respondsToSelector:@selector(sortViewClickByWork:)]){
        CourseWorkState state;
        switch (button.tag) {
            case 1:
                state = CourseWorkStataAll;
                break;
                case 2:
                state = CourseWorkStataWorking;
                break;
                case 3:
                state = CourseWorkStataWillBegin;
                break;
                case 4:
                state = CourseWorkStataEnd;
                break;
            default:
                state = CourseWorkStataAll;
                break;
        }
        [self.delegate sortViewClickByWork:state];
    }
}

- (void)bottomButtonClick:(CourseMenuButton *)button{
    [self clearButtomButtonSelectState];
    button.selectState = YES;
    if ([self.delegate respondsToSelector:@selector(sortViewClickByState:)]){
        
        CourseSortState state;
        switch (button.tag) {
            case 5:
                state = CourseSortStataAll;
                break;
            case 6:
                state = CourseSortStataHot;
                break;
            case 7:
                state = CourseSortStataNew;
                break;
            default:
                state = CourseSortStataAll;
                break;
        }
        
        [self.delegate sortViewClickByState:state];
    }
}

- (void)clearTopButtonSelectState{
    for (id subView in _topButtonBackView.subviews) {
        if ([subView isKindOfClass:[CourseMenuButton class]]){
            CourseMenuButton * subButton = subView;
            subButton.selectState = NO;
        }
    }
}

- (void)clearButtomButtonSelectState{
    for (id subView in _bottomButtonBackView.subviews) {
        if ([subView isKindOfClass:[CourseMenuButton class]]){
            CourseMenuButton * subButton = subView;
            subButton.selectState = NO;
        }
    }
}



@end

@interface CourseSortMenuView : UIView<UITableViewDelegate,UITableViewDataSource,MoreCourseTableViewCellDelegate>
@property(nonatomic,assign) CourseMenuState state;
@property (nonatomic,strong) YWTableView *courseTypeTableView;
@property (nonatomic,strong) CourseSortView *sortView;
@property (nonatomic,strong) NSArray *courseTypeArray;
@property(nonatomic,assign) BOOL isAnimation;

@property (nonatomic,weak) id <CourseSortMenuViewDelegate> delegate;
- (void)presentCourseTypeTableViewInView:(UIView *)view;
- (void)presentCourseSortViewInView:(UIView *)view;
@end

@implementation CourseSortMenuView

- (void)presentCourseTypeTableViewInView:(UIView *)view{
    [view addSubview:self];
    [self reloadTableViewWhenShowTypeList];
}
- (void)presentCourseSortViewInView:(UIView *)view{
    if (_isAnimation) return;
    _isAnimation = YES;
    [view addSubview:self];
    _sortView.hidden = NO;
    _sortView.frame = CGRectMake(0, -100, kScreenWidth, 100);
    [UIView animateWithDuration:0.3 animations:^{
        _sortView.top = 0;
    }  completion:^(BOOL finished) {
        _isAnimation = NO;
    }];
    _courseTypeTableView.hidden = YES;
}

- (void)reloadTableViewWhenShowTypeList
{
    if (_isAnimation) return;
    _isAnimation = YES;
    _sortView.hidden = YES;
    _courseTypeTableView.hidden = NO;
    if (!_courseTypeArray || _courseTypeArray.count == 0) return;
    _courseTypeTableView.frame = CGRectMake(0, -300, kScreenWidth, 300);
    [_courseTypeTableView reloadData];
    [UIView animateWithDuration:.3 animations:^{
        _courseTypeTableView.top = 0;
    }completion:^(BOOL finished) {
        _isAnimation = NO;
    }];
}

- (void)dismissSortViewCompletion:(void(^)(void))completion{
    if (_isAnimation) return;
    _isAnimation = YES;
    [UIView animateWithDuration:.3 animations:^{
        _sortView.top = -100;
    } completion:^(BOOL finished) {
        _isAnimation = NO;
        if (finished){
            _sortView.hidden = YES;
            if (completion){
                completion();
            }
        }
    }];
}

- (void)dismissListViewCompletion:(void(^)(void))completion{
    if (_isAnimation) return;
    _isAnimation = YES;
    [UIView animateWithDuration:.3 animations:^{
        _courseTypeTableView.top = -300;
    } completion:^(BOOL finished) {
        _isAnimation = NO;
        if (finished){
            _courseTypeTableView.hidden = YES;
            if (completion){
                completion();
            }
        }
    }];
}

- (void)setDelegate:(id<CourseSortMenuViewDelegate>)delegate{
    _sortView.delegate = delegate;
    _delegate = delegate;
}

- (instancetype)init{
    self = [super init];
    if (self){
        _courseTypeArray = @[];
        self.frame = CGRectMake(0, 51, kScreenWidth, kScreenHeight - 115);
        self.backgroundColor = [UIColor colorWithRGB:0x000000 alpha:.4];
        
        _sortView = [[CourseSortView alloc]init];
        _sortView.hidden = YES;
        [self addSubview:_sortView];
        
        _courseTypeTableView = [[YWTableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _courseTypeTableView.hidden = YES;
        _courseTypeTableView.delegate = self;
        _courseTypeTableView.dataSource = self;
        [self addSubview:_courseTypeTableView];
    }
    return self;
}


#pragma mark - UITableViewDelegate


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString * reuseIdentifier = @"MoreCourseTableViewCell";
    MoreCourseTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell){
        cell = [[MoreCourseTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        cell.delegate = self;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    CourseTypeListModel * model = _courseTypeArray[indexPath.section];
    NSArray * contentArray = model.courseListModel;
    CourseTypeListModel *lModel = indexPath.row*2 < [contentArray count] ? [contentArray objectAtIndex:indexPath.row*2] : nil;
    CourseTypeListModel *rModel = indexPath.row*2+1 < [contentArray count] ? [contentArray objectAtIndex:indexPath.row*2+1] : nil;
    [cell setWithLeftModel:lModel rightModel:rModel];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    CourseTypeListModel * model = _courseTypeArray[section];
    NSInteger courseCount = model.courseListModel.count;
    return courseCount % 2 == 0 ? courseCount/2 : courseCount/2 + 1;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _courseTypeArray.count;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 37)];
    
    CALayer * lineLayer = [CALayer new];
    lineLayer.backgroundColor = kLineColor_Gray_Default.CGColor;
    lineLayer.frame = CGRectMake(0, 0, kScreenWidth, 7);
    [backView.layer addSublayer:lineLayer];
    
    UIImageView * imageView = [UIImageView new];
    imageView.image = [UIImage imageNamed:@"course_type_arrow"];
    imageView.size = CGSizeMake(22, 22);
    imageView.centerY = 25.5;
    imageView.left = 18;
    [backView addSubview:imageView];
    
    UILabel * titleLabel = [UILabel new];
    titleLabel.size = CGSizeMake(150, 37);
    titleLabel.left = imageView.right + 5;
    titleLabel.top = 7;
    titleLabel.textColor = kDark_TextColor_Default;
    titleLabel.fontSize = 15;
    [backView addSubview:titleLabel];
    
    CourseTypeListModel * model = _courseTypeArray[section];
    titleLabel.text = model.courseTypeName;
    
    return backView;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 44;
}

-(void)cellClickWithModelId:(NSString *)modelID
{
    if ([_delegate respondsToSelector:@selector(sortViewClickByModelId:)]){
        [_delegate sortViewClickByModelId:modelID];
    }
}

@end


@interface CourseSortListViewController ()<UITableViewDelegate,UITableViewDataSource,CourseSortMenuViewDelegate>
@property (nonatomic,strong) YWTableView *tableView;
@property (nonatomic,strong) NSArray *sourceData;
@property (nonatomic,strong) CourseSortMenuView *menuView;
@end

@implementation CourseSortListViewController

-(instancetype)init
{
    self = [super init];
    if (self){
        self.sortState = CourseSortStataNew;
        self.workState = CourseWorkStataAll;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.showNavigationBar = YES;
    [self setControllerTitle:self.pageTitle];
    _menuView = [[CourseSortMenuView alloc]init];
    _menuView.delegate = self;
    _menuView.state = CourseMenuStateNone;

    UIBarButtonItem * backItem = [UIBarButtonItem itemWithImage:@"back_icon" selectImage:@"" addTarget:self andAction:@selector(backAction)];
    self.navigationItem.leftBarButtonItem = backItem;
    
    _tableView = [[YWTableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self refreshData];
    }];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.and.bottom.mas_equalTo(self.view);
        make.top.mas_equalTo(51);
    }];
    
    [self.tableView.mj_header beginRefreshing];
    // Do any additional setup after loading the view from its nib.
}

- (void)updatePageWithObj:(id)responseObj
{
    NSDictionary * dict = [[MFWJson jsonWithObject:responseObj] toDic];
    CourseSortDataModel * model = [CourseSortDataModel yy_modelWithDictionary:dict];
    _sourceData = model.courseArray;
    if (model.courseTypeArray){
        _menuView.courseTypeArray = model.courseTypeArray;
    }
    if (_sourceData){
        [_tableView reloadData];
    }
    [_tableView.mj_header endRefreshing];
}


#pragma mark - CourseSortMenuViewDelegate

-(void)sortViewClickByState:(CourseSortState)state
{
    if (self.sortState != state){
        self.sortState = state;
        [_tableView.mj_header beginRefreshing];
        _menuView.state = CourseMenuStateNone;
        [_menuView dismissListViewCompletion:^{
            [_menuView removeFromSuperview];
        }];
    }
}

-(void)sortViewClickByWork:(CourseWorkState)state
{
    if (self.workState != state){
      self.workState = state;
        [_tableView.mj_header beginRefreshing];
        _menuView.state = CourseMenuStateNone;
        [_menuView dismissListViewCompletion:^{
            [_menuView removeFromSuperview];
        }];
    }
}
//status  sortType classifyId
-(void)sortViewClickByModelId:(NSString *)modelId
{
    self.courseTypeId = modelId;
    [_tableView.mj_header beginRefreshing];
    _menuView.state = CourseMenuStateNone;
    [_menuView dismissListViewCompletion:^{
        [_menuView removeFromSuperview];
    }];
}

- (void)refreshData
{
    NSString * status = [NSString stringWithFormat:@"%lu",self.sortState + 1];
    NSString * sort = [NSString stringWithFormat:@"%lu",self.workState + 1];
    NSMutableDictionary  * params = @{}.mutableCopy;
    if (self.courseTypeId && self.courseTypeId)
    {
        [params setObject:self.courseTypeId forKey:@"classifyId"];
    }
    if (self.workState != CourseWorkStataAll){
        [params setObject:sort forKey:@"status"];
    }
    [params setObject:status forKey:@"sortType"];
    
    [BaseHttpTool get:kAPI_HOME_COURSE params:params success:^(id responseObj) {
        [self updatePageWithObj:responseObj];
    } failure:^(NSError *error) {
        [_tableView.mj_header endRefreshing];
        [self.view showTip:error.localizedDescription];
    }];
}

#pragma mark tableView Delegate

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * reuserIndentifier = @"CourseTableViewCell";
    CourseTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuserIndentifier];
    if (!cell){
        cell = [[CourseTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuserIndentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
  
    CourseModel * model = _sourceData[indexPath.row];
    [cell.courseImageView sd_setImageWithURL:[NSURL URLWithString:kAPI_IMAGE_HOST(model.courseImage)] randomPlaceHolder:YES];
    cell.courseName.text = model.courseName;
    cell.coursePrice.text = [NSString stringWithFormat:@"%@%@",@"¥",model.coursePrice];
    cell.courseTeacher.text = model.courseTeacher;
    cell.courseStudentCount.text = model.studentCount;
    cell.courseTeacherTitle.text = model.courseTeacherTitle;
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _sourceData.count;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    CourseModel * model = _sourceData[indexPath.row];
    CourseDetailViewController * detailController = [CourseDetailViewController new];
    detailController.courseId = model.courseId;
    [self.navigationController pushViewController:detailController animated:YES];
}

- (void)backAction{
    [self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)courseListAction:(id)sender {
    if (_menuView.isAnimation) return;
    if (_menuView.state == CourseMenuStateNone){
        if (_menuView.courseTypeArray.count == 0) return;
        _menuView.state = CourseMenuStateShowCourse;
        [_menuView presentCourseTypeTableViewInView:self.view];
    }else {
        _menuView.state = CourseMenuStateNone;
        [_menuView dismissListViewCompletion:^{
            [_menuView removeFromSuperview];
        }];
    }
}
- (IBAction)courseSortMenu:(id)sender {
    if (_menuView.isAnimation) return;
    if (_menuView.state == CourseMenuStateNone){
        _menuView.state = CourseMenuStateShowSort;
        [_menuView presentCourseSortViewInView:self.view];
    }else {
        _menuView.state = CourseMenuStateNone;
        [_menuView dismissSortViewCompletion:^{
            [_menuView removeFromSuperview];
        }];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
